<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\workflow;

use lflow\access\Page;
use lflow\access\QueryFilter;
use lflow\entity\Surrogate;
use lflow\helper\AssertHelper;
use lflow\helper\StringHelper;
use lflow\IManagerService;
use lflow\WorkFlowException;

/**
 * 管理服务类
 *
 * @author Mr.April
 * @since  1.0
 */
class ManagerService extends AccessService implements IManagerService
{

    public function saveOrUpdate(Surrogate $surrogate): void
    {
        AssertHelper::notNull($surrogate);
        $surrogate->setState(self::STATE_ACTIVE);
        if (StringHelper::isEmpty($surrogate->getId())) {
            $surrogate->setId(StringHelper::getPrimaryKey());
            $this->access()->saveSurrogate($surrogate);
        } else {
            $this->access()->updateSurrogate($surrogate);
        }
    }

    public function deleteSurrogate(string $id): void
    {
        try {
            $surrogate = $this->getSurrogate($id);
            AssertHelper::notNull($surrogate);
            $this->access()->deleteSurrogate($surrogate);
        } catch (WorkFlowException $e) {
            throw new WorkFlowException($e->getMessage());
        }
    }

    public function getSurrogate(string $id): ?Surrogate
    {
        return $this->access()->getSurrogate($id);
    }

    public function getSurrogates(string $operator, string $processName = ''): array
    {
        AssertHelper::notEmpty($operator);
        $filter = (new QueryFilter())->setOperator($operator)->setOperateTime(DateHelper::getTime());
        if (!empty($processName)) {
            $filter->setName($processName);
        }
        $surrogates = getSurrogateList($filter, null);
        if (empty($surrogates)) {
            return [];
        }
        return $surrogates;
    }

    public function getSurrogateList(QueryFilter $filter, Page $page = null): array
    {
        AssertHelper::notNull($filter);
        return $this->access()->getSurrogateList($filter, $page);
    }
}
